import mitt from 'mitt'
import type { Handler } from 'mitt'
import ReconnectingWebSocket from 'reconnecting-websocket'
import { ReceiveMessageType, SendMessageType, userTypeMap } from '@/common/constants'
import type { IRegisterData, ISendSingleMessageData, PlainObject } from '@/common/types'

class Bridge {
  private socket: ReconnectingWebSocket
  private event = mitt()

  public ready(callback: () => void) {
    this.socket = new ReconnectingWebSocket('ws://8.129.39.183:3333', [], {
      debug: true
    })
    this.socket.addEventListener('open', callback)

    this.socket.addEventListener('message', (res) => {
      const payload = JSON.parse(res.data)
      const { type, ...data } = payload.data as PlainObject
      this.event.emit(type, data)
    })
  }

  public sendMessage<T = any>(type: SendMessageType, data: T) {
    const message = JSON.stringify({
      type,
      ...data
    })
    this.socket.send(message)
  }

  public receiveMessage(type: ReceiveMessageType, callback: Handler<PlainObject>) {
    this.event.on(type, callback)
  }
  public register({ userType, ...data }: IRegisterData) {
    this.sendMessage(SendMessageType.REGISTER, {
      ...data,
      userType: userTypeMap[userType]
    })
  }

  public sendSingleMessage(data: ISendSingleMessageData) {
    const { serviceId, visitorId, ...restData } = data
    this.sendMessage(SendMessageType.SINGLE_SENDING, {
      ...restData,
      kefuCode: serviceId,
      fangkeCode: visitorId
    })
  }
}

export default new Bridge()
